package com.life.interceptor;


import com.life.properties.JwtProperties;
import com.life.utils.JwtUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 拦截请求，校验jwt令牌
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        //1、从请求头中获取令牌
        String authorization = request.getHeader(jwtProperties.getTokenName());
        try {
            //2、清除Bearer前缀
            String token = authorization.replace(jwtProperties.getTokenPrefix(), "").trim();
            //3、校验令牌
            log.info("jwt校验:{}", token);
            JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
            //4、通过，放行
            return true;
        } catch (ExpiredJwtException ex) {
            log.error("用户凭据已过期，请重新登录");
            throw new ExpiredJwtException(null, null, "用户凭据已过期，请重新登录");
        } catch (Exception e) {
            log.error("用户凭据无效，请重新登录");
            response.setStatus(401);
            return false;
        }
    }
}
